using System.Threading.Tasks;
using Api.Dto;
using Api.Model;
using Api.Repository;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Api.Controllers;

[ApiController]
[Route("api/[controller]")]

public class BlogsController : ControllerBase
{
    private readonly AdminDbContext _db;
    public readonly IRepository<Blogs> _blogsRep;
    public BlogsController(AdminDbContext db, IRepository<Blogs> blogsRep)
    {
        _db = db;
        _blogsRep = blogsRep;
    }
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        // _db.Blogs.Add(new Blogs { Title = "fsda", Author = "fsdg", Content = "fd" });
        // _db.SaveChanges();
        // var connectString = "server=localhost;database=admin1;uid=root;pwd=123456;";
        // var options = new DbContextOptionsBuilder<AdminDbContext>()
        // .UseMySql(connectString, ServerVersion.AutoDetect(connectString))
        // .Options;
        // var context = new AdminDbContext(options);
        // context.Blogs.Add(new Blogs { Title = "fsda", Author = "fsdg", Content = "fd" });
        // context.SaveChanges();
        var list = await _db.Blogs.ToListAsync();
        var res = ApiResultDto<List<Blogs>>.Success(list);
        return Ok(res);
    }
    [HttpPost]
    public async Task<IActionResult> Post(BlogCreateDto blogCreateDto)
    {
        var blog = new Blogs { Title = blogCreateDto.Title, Author = blogCreateDto.Author, Content = blogCreateDto.Content };
        // var obj = _db.Blogs.Add(blog).Entity;
        // _db.SaveChanges();
        var obj = await _blogsRep.CreateAsync(blog);

        // var objConvert = new BlogResultDto(obj.Title, obj.Author, obj.Content);
        var res = ApiResultDto<Blogs>.Success(obj);
        return Ok(res);
    }
    [HttpPut("{id}")]
    public async Task<IActionResult> Put(Guid id, BlogUpdateDto blogUpdateDto)
    {
        var blog = _db.Blogs.FirstOrDefault(x => x.Id == id);
        if (blog == null)
        {
            var res = ApiResultDto<object>.Error();
            return Ok(res);
        }
        blog.Title = blogUpdateDto.Title;
        blog.Author = blogUpdateDto.Author;
        blog.Content = blogUpdateDto.Content;

        await _blogsRep.UpdateAsync(blog);

        _db.SaveChanges();
        var successRes = ApiResultDto<Blogs>.Success(blog);
        return Ok(successRes);
    }
    [HttpDelete("{id}")]
    public async Task<IActionResult> Del(Guid id)
    {
        var blog = _db.Blogs.Find(id);
        if (blog == null)
        {
            return Ok(ApiResultDto<object>.Error());

        }
        await _blogsRep.DeleteAsync(blog);
        _db.SaveChanges();
        return Ok(ApiResultDto<Blogs>.Success(blog));
    }
}